<template>
  <div class="environment-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>环境管理</span>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加环境
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="环境名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入环境名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="环境类型">
            <el-select
              v-model="searchForm.type"
              placeholder="请选择环境类型"
              clearable
              style="width: 150px"
            >
              <el-option label="开发环境" value="dev" />
              <el-option label="测试环境" value="test" />
              <el-option label="预发布环境" value="staging" />
              <el-option label="生产环境" value="prod" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 120px"
            >
              <el-option label="正常" value="normal" />
              <el-option label="维护中" value="maintenance" />
              <el-option label="停用" value="disabled" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 环境表格 -->
      <el-table
        :data="environmentList"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="环境名称" min-width="150" />
        <el-table-column prop="code" label="环境代码" width="120" />
        <el-table-column prop="type" label="环境类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="hostCount" label="主机数量" width="100" />
        <el-table-column prop="hostGroupCount" label="主机组数量" width="120" />
        <el-table-column prop="region" label="所属区域" width="120" />
        <el-table-column prop="network" label="网络配置" min-width="200">
          <template #default="{ row }">
            <div class="network-info">
              <div>VPC: {{ row.network.vpc }}</div>
              <div>子网: {{ row.network.subnet }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="showDetailDialog(row)"
            >
              详情
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="showEditDialog(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
              :disabled="row.hostCount > 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑环境对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="环境名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入环境名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="环境代码" prop="code">
              <el-input v-model="form.code" placeholder="请输入环境代码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="环境类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择环境类型" style="width: 100%">
                <el-option label="开发环境" value="dev" />
                <el-option label="测试环境" value="test" />
                <el-option label="预发布环境" value="staging" />
                <el-option label="生产环境" value="prod" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属区域" prop="region">
              <el-select v-model="form.region" placeholder="请选择区域" style="width: 100%">
                <el-option label="华北-北京" value="cn-north-1" />
                <el-option label="华东-上海" value="cn-east-1" />
                <el-option label="华南-广州" value="cn-south-1" />
                <el-option label="西南-成都" value="cn-southwest-1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 网络配置 -->
        <el-form-item label="网络配置">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="VPC" prop="network.vpc">
                <el-input v-model="form.network.vpc" placeholder="请输入VPC ID" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="子网" prop="network.subnet">
                <el-input v-model="form.network.subnet" placeholder="请输入子网CIDR" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio value="normal">正常</el-radio>
            <el-radio value="maintenance">维护中</el-radio>
            <el-radio value="disabled">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入环境描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 环境详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="环境详情"
      width="900px"
    >
      <div class="detail-content" v-if="currentEnvironment">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="环境名称">
            {{ currentEnvironment.name }}
          </el-descriptions-item>
          <el-descriptions-item label="环境代码">
            {{ currentEnvironment.code }}
          </el-descriptions-item>
          <el-descriptions-item label="环境类型">
            <el-tag :type="getTypeTagType(currentEnvironment.type)">
              {{ getTypeLabel(currentEnvironment.type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(currentEnvironment.status)">
              {{ getStatusLabel(currentEnvironment.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="所属区域">
            {{ currentEnvironment.region }}
          </el-descriptions-item>
          <el-descriptions-item label="主机数量">
            {{ currentEnvironment.hostCount }}
          </el-descriptions-item>
          <el-descriptions-item label="主机组数量">
            {{ currentEnvironment.hostGroupCount }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ currentEnvironment.createTime }}
          </el-descriptions-item>
          <el-descriptions-item label="VPC" span="2">
            {{ currentEnvironment.network.vpc }}
          </el-descriptions-item>
          <el-descriptions-item label="子网" span="2">
            {{ currentEnvironment.network.subnet }}
          </el-descriptions-item>
          <el-descriptions-item label="描述" span="2">
            {{ currentEnvironment.description }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search
} from '@element-plus/icons-vue'

// 注册图标组件
const iconComponents = {
  Plus,
  Search
}

// 接口定义
interface Environment {
  id: string
  name: string
  code: string
  type: string
  status: string
  hostCount: number
  hostGroupCount: number
  region: string
  network: {
    vpc: string
    subnet: string
  }
  description: string
  createTime: string
}

interface SearchForm {
  name: string
  type: string
  status: string
}

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogTitle = ref('添加环境')
const isEdit = ref(false)
const currentEnvironment = ref<Environment | null>(null)

// 搜索表单
const searchForm = reactive<SearchForm>({
  name: '',
  type: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 环境列表
const environmentList = ref<Environment[]>([])

// 表单数据
const form = reactive<Environment>({
  id: '',
  name: '',
  code: '',
  type: '',
  status: 'normal',
  hostCount: 0,
  hostGroupCount: 0,
  region: '',
  network: {
    vpc: '',
    subnet: ''
  },
  description: '',
  createTime: ''
})

// 表单引用
const formRef = ref()

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入环境名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入环境代码', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z][a-zA-Z0-9_-]*$/,
      message: '环境代码必须以字母开头，只能包含字母、数字、下划线和连字符',
      trigger: 'blur'
    }
  ],
  type: [
    { required: true, message: '请选择环境类型', trigger: 'change' }
  ],
  region: [
    { required: true, message: '请选择所属区域', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 模拟数据
const mockData: Environment[] = [
  {
    id: 'ENV001',
    name: '生产环境',
    code: 'prod',
    type: 'prod',
    status: 'normal',
    hostCount: 25,
    hostGroupCount: 5,
    region: 'cn-north-1',
    network: {
      vpc: 'vpc-prod-001',
      subnet: '10.0.1.0/24'
    },
    description: '生产环境，承载核心业务系统',
    createTime: '2024-01-10 10:00:00'
  },
  {
    id: 'ENV002',
    name: '测试环境',
    code: 'test',
    type: 'test',
    status: 'normal',
    hostCount: 12,
    hostGroupCount: 3,
    region: 'cn-east-1',
    network: {
      vpc: 'vpc-test-001',
      subnet: '10.1.1.0/24'
    },
    description: '测试环境，用于功能测试和集成测试',
    createTime: '2024-01-08 14:30:00'
  },
  {
    id: 'ENV003',
    name: '开发环境',
    code: 'dev',
    type: 'dev',
    status: 'maintenance',
    hostCount: 8,
    hostGroupCount: 2,
    region: 'cn-south-1',
    network: {
      vpc: 'vpc-dev-001',
      subnet: '10.2.1.0/24'
    },
    description: '开发环境，供开发人员使用',
    createTime: '2024-01-05 09:15:00'
  }
]

// 获取环境类型标签类型
const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    dev: 'info',
    test: 'warning',
    staging: 'primary',
    prod: 'danger'
  }
  return typeMap[type] || 'info'
}

// 获取环境类型标签文本
const getTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    dev: '开发环境',
    test: '测试环境',
    staging: '预发布环境',
    prod: '生产环境'
  }
  return typeMap[type] || type
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    normal: 'success',
    maintenance: 'warning',
    disabled: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status: string) => {
  const statusMap: Record<string, string> = {
    normal: '正常',
    maintenance: '维护中',
    disabled: '停用'
  }
  return statusMap[status] || status
}

// 获取环境列表
const fetchEnvironmentList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    // 应用搜索过滤
    let filteredData = [...mockData]
    if (searchForm.name) {
      filteredData = filteredData.filter(item =>
        item.name.includes(searchForm.name) || item.code.includes(searchForm.name)
      )
    }
    if (searchForm.type) {
      filteredData = filteredData.filter(item => item.type === searchForm.type)
    }
    if (searchForm.status) {
      filteredData = filteredData.filter(item => item.status === searchForm.status)
    }

    pagination.total = filteredData.length
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    environmentList.value = filteredData.slice(start, end)
  } catch (error) {
    ElMessage.error('获取环境列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchEnvironmentList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    type: '',
    status: ''
  })
  pagination.currentPage = 1
  fetchEnvironmentList()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchEnvironmentList()
}

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchEnvironmentList()
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加环境'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (row: Environment) => {
  dialogTitle.value = '编辑环境'
  isEdit.value = true
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 显示详情对话框
const showDetailDialog = (row: Environment) => {
  currentEnvironment.value = row
  detailDialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: '',
    name: '',
    code: '',
    type: '',
    status: 'normal',
    hostCount: 0,
    hostGroupCount: 0,
    region: '',
    network: {
      vpc: '',
      subnet: ''
    },
    description: '',
    createTime: ''
  })
  formRef.value?.resetFields()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))

        ElMessage.success(`${isEdit.value ? '更新' : '创建'}成功`)
        dialogVisible.value = false
        fetchEnvironmentList()
      } catch (error) {
        ElMessage.error(`${isEdit.value ? '更新' : '创建'}失败`)
      }
    }
  })
}

// 删除环境
const handleDelete = async (row: Environment) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除环境 "${row.name}" 吗？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    ElMessage.success('删除成功')
    fetchEnvironmentList()
  } catch (error) {
    // 用户取消操作
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchEnvironmentList()
})
</script>

<style scoped>
.environment-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.02);
  border-radius: 8px;
  border: 1px solid rgba(120, 220, 255, 0.1);
}

.network-info {
  font-size: 12px;
  color: var(--tech-text-secondary);
}

.network-info div {
  margin-bottom: 2px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.detail-content {
  padding: 10px 0;
}
</style>
